from bs4 import BeautifulSoup
import urllib.request
import os
from time import time

class AudioItem(object):
    def __init__(self, name, url):
        self.name = name
        self.url = url

DEFAULT_UA = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57."
HOST = 'http://radio.cnwest.com'
CURRENT_DIR = os.path.realpath(__file__)
FILES_STORE = os.path.join(CURRENT_DIR, '..', 'files')

def main():
    list = parseListPage()
    if len(list) == 0:
        print('没有数据，无法下载')
        return
    for inx, itm in enumerate(list):
        print('[%s]\t%s'%(inx, itm.name))
    print('请输入序号进行下载(直接回车退出)：')
    while True:
        line = input()
        try:
            if line.strip() == '':
                break
            index = int(line)            
            if index < 0 or index > len(list) - 1:
                raise ValueError()
                
            print('开始下载...')
            start = time()
            downloadAudio(list[index])
            print('下载完成，耗时%.2f秒' % (time() - start))
            
        except ValueError as err:
            print('请输入%s - %s 之间的有效数字' % (0, len(list) - 1))
    
def downloadAudio(audio_item):
    soup = getBS(audio_item.url)
    audio_url = soup.select('#MediaPlayer')[0].find(attrs = {'name' : 'filename'})['value']
    audio_item.child_url = audio_url

    request = urllib.request.Request(audio_url)
    request.add_header('User-Agent', DEFAULT_UA)
    response = urllib.request.urlopen(request)

    file = response.read()
    ext = os.path.splitext(audio_url)[-1]
    if not os.path.isdir(FILES_STORE):
        os.makedirs(FILES_STORE)
    with open(os.path.join(FILES_STORE, '%s%s' % (audio_item.name, ext)), 'wb') as f:
        f.write(file)
        f.close()
    return audio_item

def parseListPage():
    soup = getBS()
    td_columns = soup.find_all('td', class_='tt_black2')
    list = []
    for (i, td) in enumerate(td_columns):
        name = td.get_text().strip()
        url = '%s/%s' % (HOST, td.find('a')['href'])
        list.append(AudioItem(name, url))
    return list
def getBS(url = HOST + '/node_12942.htm'):
    req = urllib.request.Request(url)
    req.add_header("User-Agent", DEFAULT_UA)
    response = urllib.request.urlopen(req)
    
    return BeautifulSoup(response.read(), 'html.parser')

main()